// pages/order_detail/index.js
Page({
  data: {
    navBarHeight: 0,
    contentTop: 0,
    bottomSafeArea: 0,
    orderId: '',
    orderData: null,
    loading: true,
    hideBottomBtn: false, // 是否隐藏底部按钮
    showReviewModal: false, // 评价弹窗显示状态
    rating: 0, // 评分
    reviewText: '', // 评价内容
    isSubmitting: false, // 提交中状态
    canSubmit: false // 是否可以提交评价
  },

  // 订单状态映射
  orderStatusMap: {
    'pending_payment': '已取消',
    'pending_shipment': '待发货',
    'pending_receipt': '待收货',
    'pending_review': '待评价',
    'completed': '已完成'
  },

  onLoad(options) {
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    // 只有明确传入 hideBottomBtn=true 时才隐藏按钮，否则根据订单状态显示
    const shouldHideBtn = options.hideBottomBtn === 'true'
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      bottomSafeArea,
      orderId: options.orderId,
      hideBottomBtn: shouldHideBtn
    })
    
    console.log('页面参数:', options, '隐藏按钮:', shouldHideBtn)
    
    if (options.orderId) {
      this.loadOrderDetail(options.orderId)
    }
  },

  // 加载订单详情
  async loadOrderDetail(orderId) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      
      const db = wx.cloud.database()
      const result = await db.collection('orders').doc(orderId).get()
      
      if (result.data) {
        const orderData = result.data
        
        
        // 处理商品数据，添加格式化的价格和小计
        const processedItems = orderData.items.map(item => {
          // 确保价格是数字类型
          const price = parseFloat(item.finalPrice || item.price || 0)
          const quantity = parseInt(item.quantity || 1)
          const subtotal = price * quantity
          
          // 计算价格偏移量
          let priceOffsetFormatted = ''
          let discountAmountFormatted = ''
          const basePrice = parseFloat(item.basePrice || 0)
          if (basePrice && price !== basePrice) {
            const priceDiff = Math.abs(price - basePrice)
            const formattedDiff = priceDiff.toFixed(2)
            if (price > basePrice) {
              priceOffsetFormatted = formattedDiff
            } else {
              discountAmountFormatted = formattedDiff
            }
          }
          
          return {
            ...item,
            price: price,
            priceFormatted: price.toFixed(2),
            quantity: quantity,
            subtotal: subtotal.toFixed(2),
            priceOffsetFormatted,
            discountAmountFormatted
          }
        })
        
        // 处理时间和支付方式
        const createTime = orderData.createTime || orderData.createdAt
        const createTimeFormatted = createTime ? this.formatTime(createTime) : ''
        
        // 处理支付方式
        let paymentMethodFormatted = '未支付'
        if (orderData.paymentMethods && orderData.paymentMethods.length > 0) {
          const paymentMethods = orderData.paymentMethods.map(method => {
            switch (method.id) {
              case 'balance':
                return `余额支付 ¥${method.amount.toFixed(2)}`
              case 'wechat':
                return `微信支付 ¥${method.amount.toFixed(2)}`
              case 'alipay':
                return `支付宝 ¥${method.amount.toFixed(2)}`
              case 'combo':
                return `组合支付 ¥${method.amount.toFixed(2)}`
              default:
                return `${method.id} ¥${method.amount.toFixed(2)}`
            }
          })
          paymentMethodFormatted = paymentMethods.join(' + ')
        } else if (orderData.payTime) {
          paymentMethodFormatted = '已支付'
        }

        // 添加中文状态文本
        const statusMap = {
          'pending_payment': '已取消',
          'pending_shipment': '待发货',
          'pending_receipt': '待收货',
          'pending_review': '待评价',
          'completed': '已完成'
        }
        const statusText = statusMap[orderData.status] || orderData.status

        this.setData({
          orderData: {
            ...orderData,
            items: processedItems,
            createTimeFormatted,
            paymentMethodFormatted,
            statusText
          },
          totalAmountFormatted: orderData.totalAmount.toFixed(2),
          discountAmountFormatted: orderData.discountAmount ? orderData.discountAmount.toFixed(2) : '0.00',
          actualAmountFormatted: orderData.actualAmount.toFixed(2),
          loading: false
        })
        
        // 调试信息
        console.log('订单数据加载完成:', {
          status: orderData.status,
          statusText: statusText,
          loading: this.data.loading,
          hideBottomBtn: this.data.hideBottomBtn,
          orderData: !!this.data.orderData,
          showBottomBar: !this.data.loading && !this.data.hideBottomBtn && !!this.data.orderData,
          isPendingReview: orderData.status === 'pending_review'
        })
        
        // 强制更新页面
        this.$forceUpdate && this.$forceUpdate()
      } else {
        throw new Error('订单不存在')
      }
      
    } catch (error) {
      console.error('加载订单详情失败:', error)
      wx.showToast({
        title: '订单加载失败',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      wx.hideLoading()
    }
  },

  // 返回按钮
  handleBack() {
    wx.navigateBack()
  },

  // 格式化时间
  formatTime(date) {
    if (!date) return ''
    
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hour = String(d.getHours()).padStart(2, '0')
    const minute = String(d.getMinutes()).padStart(2, '0')
    const second = String(d.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  },

  // 继续购物
  continueShopping() {
    wx.switchTab({
      url: '/pages/shop/index'
    })
  },

  // 打开评价弹窗
  openReviewModal() {
    this.setData({
      showReviewModal: true,
      rating: 0,
      reviewText: '',
      canSubmit: false
    })
  },

  // 关闭评价弹窗
  closeReviewModal() {
    this.setData({
      showReviewModal: false,
      rating: 0,
      reviewText: '',
      canSubmit: false
    })
  },

  // 跳过评价，直接完成订单
  async skipReview() {
    try {
      wx.showLoading({
        title: '处理中...',
        mask: true
      })

      // 调用云函数更新订单状态为已完成
      const result = await wx.cloud.callFunction({
        name: 'updateOrderStatus',
        data: {
          orderId: this.data.orderId,
          status: 'completed',
          skipReview: true
        }
      })

      if (result.result && result.result.success) {
        wx.showToast({
          title: '已跳过评价',
          icon: 'success',
          duration: 1500
        })
        
        // 关闭评价弹窗
        this.closeReviewModal()
        
        // 重新加载订单详情以更新状态
        this.loadOrderDetail(this.data.orderId)
        
      } else {
        wx.showToast({
          title: result.result?.message || '订单更新失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('跳过评价失败:', error)
      
      // 根据错误类型提供不同提示
      let errorMessage = '操作失败，请重试'
      if (error.errCode === -501000) {
        errorMessage = '云函数调用失败'
      } else if (error.errMsg && error.errMsg.includes('network')) {
        errorMessage = '网络错误，请检查网络连接'
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 阻止冒泡
  stopPropagation() {
    // 空函数，用于阻止冒泡
  },

  // 选择评分
  selectRating(e) {
    const rating = e.currentTarget.dataset.rating
    this.setData({ 
      rating,
      canSubmit: rating > 0 && this.data.reviewText.trim().length > 0
    })
  },

  // 输入评价内容
  onReviewInput(e) {
    const reviewText = e.detail.value
    this.setData({
      reviewText,
      canSubmit: this.data.rating > 0 && reviewText.trim().length > 0
    })
  },

  // 提交评价
  async submitReview() {
    // 检查是否可以提交
    if (!this.data.canSubmit) {
      return
    }

    if (this.data.rating === 0) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      })
      return
    }

    if (!this.data.reviewText.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      })
      return
    }

    this.setData({ isSubmitting: true })

    try {
      const result = await wx.cloud.callFunction({
        name: 'submitProductReview',
        data: {
          orderId: this.data.orderId,
          productId: this.data.orderData.items[0].productId,
          rating: this.data.rating,
          comment: this.data.reviewText.trim()
        }
      })

      if (result.result && result.result.success) {
        wx.showToast({
          title: '评价成功',
          icon: 'success'
        })
        
        this.closeReviewModal()
        
        // 重新加载订单详情
        this.loadOrderDetail(this.data.orderId)
        
      } else {
        wx.showToast({
          title: result.result?.message || '评价失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('提交评价失败:', error)
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ isSubmitting: false })
    }
  }
})